import React, { Component } from 'react';
import { Modal, Input, Button, message, Icon } from 'antd';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { bindActionCreators } from 'redux';
import ColorBlocks from '@components/color-blocks';
import { addTag, updateTag, deleteTag } from '@api/tag';
import { batchUpdateAssets } from '@api/asset';
import { actions as tagActions } from '@redux/reducer/tag';
import cn from 'classnames';
import './index.less';

class AddTagModal extends Component {
  constructor(props) {
    super(props);
    this.state = _.cloneDeep(AddTagModal.defaultProps);
  }

  static defaultProps = {
    tagName: '',
    tagId: '',
    search: '',
    editId: '',
    editName: '',
    editColor: '#1890ff',
    onUpdatingTag: false,
    onDeletingTag: false,
    batchAddTagging: false,
    mode: 'select'
  };

  static getDerivedStateFromProps(props) {
    if (!props.visible) {
      return _.cloneDeep(AddTagModal.defaultProps);
    }
  }

  static propTypes = {
    tags: PropTypes.array,
    siteIds: PropTypes.array,
    loadAssets: PropTypes.func,
    visible: PropTypes.bool,
    onClose: PropTypes.func,
    loadTags: PropTypes.func
  };

  checkTag = (tagName, tagId) => {
    this.setState({
      tagName,
      tagId,
      search: tagName
    });
  };

  onInputChange = type => {
    return e => {
      this.setState({ [type]: e.target.value.replace(/\s/g, '') });
    };
  };

  onBatchAddTag = () => {
    const { tagId } = this.state;
    if (!tagId) {
      return message.info('请选择标签');
    }
    this.setState({ batchAddTagging: true });
    // eslint-disable-next-line
    batchUpdateAssets({ query: { siteIds: this.props.siteIds }, push: { tag_oids: [tagId] } })
      .then(() => {
        message.success('添加标签成功!');
        this.props.onClose();
        this.props.loadAssets();
      })
      .catch(() => {
        message.error('添加标签失败!');
      })
      .finally(() => {
        this.setState({ batchAddTagging: false });
      });
  };

  onSelectColor = editColor => {
    this.setState({ editColor });
  };

  onUpdateTag = () => {
    const { tags = [] } = this.props;
    const { editName: name, editColor: color, editId: tagId, mode } = this.state;
    if (name.length > 32) {
      return;
    }
    if (!name) {
      return message.info('标签名不能为空');
    }
    if (
      (mode === 'new-add' && tags.some(tag => tag.name === name)) ||
      (mode === 'edit' && tags.some(tag => tag.name === name && tag._id !== tagId))
    ) {
      return message.info('请勿重复添加标签');
    }
    this.setState({ onUpdatingTag: true });
    if (mode === 'new-add') {
      addTag({ name, color })
        .then(res => {
          const tagId = _.get(res.data, 'data.tag._id', '');
          message.success('新增标签成功');
          this.props.loadTags();
          this.setState({
            tagId,
            editName: '',
            editColor: '#1890ff'
          });
        })
        .catch(() => {
          message.error('新增标签失败');
        })
        .finally(() => {
          this.onBatchAddTag();
          this.setState({ onUpdatingTag: false });
        });
    } else {
      // eslint-disable-next-line
      updateTag({ name, color, tag_id: tagId })
        .then(() => {
          message.success('修改标签成功');
          this.props.loadTags();
        })
        .catch(() => {
          message.error('修改标签失败');
        })
        .finally(() => {
          this.setState({ onUpdatingTag: false });
        });
    }
  };

  onDeleteTag = () => {
    const { editId: tagId } = this.state;
    if (!tagId) {
      window.console.log('标签无ID');
      return message.error('修改标签失败');
    }
    this.setState({ onDeletingTag: true });
    // eslint-disable-next-line
    deleteTag({ tag_id: tagId })
      .then(() => {
        message.success('删除标签成功');
        this.props.loadTags();
        this.setState({
          mode: 'select',
          editName: '',
          editColor: '#1890ff'
        });
      })
      .catch(() => {
        message.error('删除标签失败');
      })
      .finally(() => {
        this.setState({ onDeletingTag: false });
      });
  };

  onSetEditMode = ({ color, name, _id }) => {
    return e => {
      e.stopPropagation();
      this.setState({
        mode: 'edit',
        editId: _id,
        editName: name,
        editColor: color
      });
    };
  };

  onSetAddMode = () => {
    this.setState({
      mode: 'new-add',
      editId: '',
      editName: '',
      editColor: '#1890ff'
    });
  };

  render() {
    const {
      tagId,
      search,
      mode,
      editName,
      editColor,
      onUpdatingTag,
      batchAddTagging,
      onDeletingTag
    } = this.state;
    const { tags = [], visible, onClose } = this.props;

    const titleMap = {
      edit: '编辑标签',
      'new-add': '新增标签',
      select: '添加标签'
    };

    return (
      <Modal
        maskClosable={false}
        width={300}
        visible={visible}
        title={titleMap[mode]}
        onCancel={onClose}
        className="padding-24 bottom-center no-header-bottom-lines add-tag-modal"
        confirmLoading={batchAddTagging}
        onOk={this.onBatchAddTag}
        {...(mode === 'select' ? {} : { footer: null })}
      >
        {mode === 'select' ? (
          <div className="select">
            <div className="search-input">
              <Input
                placeholder="搜索标签"
                value={search}
                onChange={this.onInputChange('search')}
              />
              <Icon type="plus-circle" onClick={this.onSetAddMode} />
            </div>
            <div className="tag-list">
              {tags
                .filter(({ name }) => name.includes(search))
                .map(({ color, name, _id }) => (
                  <div key={_id} className="tag-item" onClick={() => this.checkTag(name, _id)}>
                    <i style={{ backgroundColor: color || '#1890ff' }} className="icon" />
                    <span className="value">{name}</span>
                    <Icon
                      type="edit"
                      className="edit"
                      onClick={this.onSetEditMode({ color, name, _id })}
                    />
                    {tagId === _id && <Icon type="check" className="check" />}
                  </div>
                ))}
            </div>
          </div>
        ) : (
          <div className="add-update">
            <Icon type="left" onClick={() => this.setState({ mode: 'select' })} />
            <Input
              placeholder="标签名称（不超过32个字符）"
              value={editName}
              onChange={this.onInputChange('editName')}
            />
            <div className={cn('error', { show: editName.length > 32 })}>
              标签名长度不能超过32个字符
            </div>
            <ColorBlocks selectColor={editColor} onClick={this.onSelectColor} />
            {mode === 'new-add' ? (
              <div className="add-btn-wrapper">
                <Button
                  type="primary"
                  style={{ width: '100%' }}
                  onClick={this.onUpdateTag}
                  loading={onUpdatingTag}
                >
                  创建
                </Button>
              </div>
            ) : (
              <div className="update-btn-wrapper">
                <Button
                  type="danger"
                  style={{ width: 100 }}
                  onClick={this.onDeleteTag}
                  loading={onDeletingTag}
                >
                  删除
                </Button>
                <Button
                  type="primary"
                  style={{ width: 100 }}
                  onClick={this.onUpdateTag}
                  loading={onUpdatingTag}
                >
                  更新
                </Button>
              </div>
            )}
          </div>
        )}
      </Modal>
    );
  }
}

const mapStateToProps = state => {
  return {
    tags: _.get(state, 'tag.tags', [])
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(tagActions, dispatch)
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(AddTagModal);
